package me.itsoo.artemis.framework.core.converter;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * StringTypeConvertor
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/18
 */
@Slf4j
public class StringTypeConvertor implements TypeConvertor {

    @Override
    public Object convertIfNecessary(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof String) {
            return value;
        }

        if (value instanceof Blob) {
            try {
                value = ((Blob) value).getBinaryStream();
            } catch (SQLException e) {
                // TODO log error
                return null;
            }
        }

        if (value instanceof Clob) {
            try {
                value = ((Clob) value).getAsciiStream();
            } catch (SQLException e) {
                // TODO log error
                return null;
            }
        }

        if (value instanceof InputStream) {
            try (InputStream is = (InputStream) value) {
                try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) {
                    try (BufferedReader br = new BufferedReader(isr)) {
                        return br.lines().collect(Collectors.joining(System.lineSeparator()));
                    }
                }
            } catch (Exception e) {
                // TODO log error
                return null;
            }
        }

        return value.toString();
    }
}
